<template>
  <section class="editor">
    <div ref="editor" :class="{'editor-error': error_}"></div>
  </section>
</template>
<script>
import wangeditor from 'wangeditor'
import mixins from './../mixins'
export default {
  name: 'VEditor',
  mixins: [mixins],
  props: {
    option: {
      type: Object,
      default: {}
    }
  },
  data () {
    return {
      editor: null,
      value: '',
      menus: [
        'head',
        'bold',
        'fontSize',
        'fontName',
        'italic',
        'underline',
        'strikeThrough',
        'indent',
        'lineHeight',
        'foreColor',
        'backColor',
        'link',
        'list',
        'justify',
        'quote',
        'image',
        'video',
        'table',
        'splitLine',
        'undo'
      ]
    }
  },
  watch: {
    disabled: {
      handler (v) {
        if (v) {
          this.editor.disable()
        } else {
          this.editor.enable()
        }
      },
      deep: true
    }
  },
  mounted () {
    this.init()
  },
  beforeDestroy () {
    if (this.editor) {
      this.editor.destroy()
      this.editor = null
    }
  },
  methods: {
    init () {
      this._ready = false
      const _this = this
      const { disabled } = this
      this.editor = new wangeditor(this.$refs.editor)
      this.editor.config.menus = this.menus
      this.editor.config.focus = false
      this.editor.config.placeholder = this.placeholder || '请输入正文'
      this.editor.config.onchange = () => {
        _this.handleChange()
        if (_this._ready) {
          _this.setCheck()
        } else {
          _this._ready = true
        }
      }
      this.editor.config.onchangeTimeout = 500
      this.editor.create()
      if (disabled) {
        this.editor.disable()
      } else {
        this.editor.enable()
      }
      this.editor.txt.html(this.option.value)
    },

    getValue () {
      return this.editor.txt.html()
    },

    setValue (v) {
      this.editor && this.editor.txt.html(v)
    },

    setCheck () {
      const { required } = this
      let error = false, error_message = ''
      if (required) {
        let t = this.getValue()
        if (t) {
          error = false
        } else {
          error = true
          error_message = '必填选项不能为空'
        }
      }
      this.error_ = error
      this.error_message_ = error_message
      this.fieldCheck()
    },

    handleChange () {
      this.dispatch_event('filed-value-change', this.getValue())
    }
  }
}
</script>
<style lang="scss" scoped>
@import '@/styles/var.scss';
.editor {
  /deep/ {
    .w-e-toolbar {
      z-index: 2 !important;
    }
    .w-e-text-container {
      z-index: 1 !important;
    }
  }
  .editor-error {
    border: 1px solid $a3;
  }
}
</style>
